package edu.cuit.zhuyimeng.ticket.service.impl;

import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheInvalidate;
import com.alicp.jetcache.anno.Cached;
import com.baomidou.dynamic.datasource.annotation.Master;
import com.baomidou.dynamic.datasource.annotation.Slave;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.cuit.zhuyimeng.framework.cache.aspect.annotation.CacheInvalidatePattern;
import edu.cuit.zhuyimeng.ticket.controller.vo.TicketInfoVO;
import edu.cuit.zhuyimeng.ticket.convert.TicketConverter;
import edu.cuit.zhuyimeng.ticket.dal.mapper.TicketMapper;
import edu.cuit.zhuyimeng.ticket.dal.po.TicketPO;
import edu.cuit.zhuyimeng.ticket.enums.CacheConstants;
import edu.cuit.zhuyimeng.ticket.service.IUserTicketManager;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户飞机票管理服务实现类
 */
@RequiredArgsConstructor
@Service
public class UserTicketManager implements IUserTicketManager {

    private final TicketMapper ticketMapper;

    private final Cache<String, TicketInfoVO> ticketInfoCache;

    @Override
    @Cached(name = CacheConstants.TICKET_INFO ,key = "args[0]")
    @Slave
    public TicketInfoVO getUserTicketInfo(String loginId) {
        TicketPO ticketPO = ticketMapper.selectOne(new LambdaQueryWrapper<TicketPO>().eq(TicketPO::getUserLoginId, loginId));
        if (ticketPO == null) {
            return null;
        }
        return TicketConverter.convertTicketInfoVO(ticketPO);
    }

    @Override
    @Master
    public void addUserTicket(String loginId,Long flightId) {
        TicketPO ticketPO = TicketPO.builder()
                .userLoginId(loginId)
                .flightId(flightId).build();
        ticketMapper.insert(ticketPO);
        ticketInfoCache.put(loginId,TicketConverter.convertTicketInfoVO(ticketPO));
    }

    @Override
    @CacheInvalidate(name = CacheConstants.TICKET_INFO, key = "args[0]")
    @Master
    public void removeUserTicket(String loginId) {
        ticketMapper.delete(new LambdaQueryWrapper<TicketPO>().eq(TicketPO::getUserLoginId,loginId));
    }

    @Override
    @CacheInvalidatePattern(name = CacheConstants.TICKET_INFO , pattern = "*")
    @CacheInvalidate(name = CacheConstants.FLIGHT_INFO , key = "args[0]")
    @Master
    public void removeFlightTicket(Long flightId) {
        ticketMapper.delete(new LambdaQueryWrapper<TicketPO>().eq(TicketPO::getFlightId,flightId));
    }
}
